let template = require('./../../template/tabbar.js');
import { getActivityList } from "../../service/onetoone_service"
import { queryAllCategory } from "../../service/jb_category_service.js"
import {
  notReadMsgNumber
} from "../../service/jb_common_service"
import { queryCategoryProductList } from "../../service/jb_product_service"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    topCategoryIndex: 0,
    topCategoryNextIndex: 1,
    topCategoryItem: null,
    topCategoryShow: false,
    topContentScrollW: 0,// 导航区宽度
    topScrollLeft: 0,//横向滚动条位置
    horizontalSwiperIndex: 100,
    topScrollArr: [
      // {
      //   title: "补水保湿"
      // },
      // {
      //   title: "术后修复"
      // },
      // {
      //   title: "控油祛痘"
      // },
      // {
      //   title: "冻龄抗衰"
      // },
      // {
      //   title: "舒敏修复"
      // },
      // {
      //   title: "美白淡斑"
      // },
      // {
      //   title: "水乳面霜"
      // },
      // {
      //   title: "原液精华"
      // },
    ],
    //顶部分类相关
    productList: [

    ],
    leftCategorySelect: {},
    leftCategoryIndex: 0,
    leftCategroyArr: [
      // {
      //   title: "全部",
      //   key: 0,
      // },
      // {
      //   title: "润白研",
      //   key: 0,
      // },
      // {
      //   title: "科颜氏",
      //   key: 0,
      // },
      // {
      //   title: "可复欣",
      //   key: 0,
      // },
      // {
      //   title: "HB康利美",
      //   key: 0,
      // },
      // {
      //   title: "可利金",
      //   key: 0,
      // },
      // {
      //   title: "兰蔻",
      //   key: 0,
      // },
      // {
      //   title: "娇兰佳人",
      //   key: 0,
      // },
      // {
      //   title: "可复欣",
      //   key: 0,
      // },
      // {
      //   title: "HB康利美",
      //   key: 0,
      // },
      // {
      //   title: "可利金",
      //   key: 0,
      // },
      // {
      //   title: "兰蔻",
      //   key: 0,
      // },
      // {
      //   title: "娇兰佳人",
      //   key: 0,
      // }
    ],
    requestParams: {
      keyword: "",
      priceOrder: '',
      salesOrder: "",
      news: 0,
      page: 1,
      limit: 20,
      cid: 0
    },
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    refreshFlag: false,
    notReadNum: 0,
    tempCategoryName: "全部",
    showRecommendPro: false,//是否显示分类推荐
    recomendProductList: [],//推荐数组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getActivityList();
    wx.hideTabBar()
    template.tabbar("tabBar", 1, this, app.globalData.cartNum)//0表示第一个tabbar
    this.ininScrollW();
    if (!app.globalData.categoryName) {
      this.queryAllCategory();
    }

    console.log("JJLog:分类过来是啥====：" + app.globalData.categoryName);
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.categoryName) {
      this.queryAllCategory();
    }
    this.notReadMsgNumber();
  },
  notReadMsgNumber() {
    notReadMsgNumber().then(res => {
      if (res.code == 200) {
        this.setData({
          notReadNum: res.data.notRead || 0
        })
      }
    }).catch(err => {

    })
  },
  //左侧点击
  bottomLeftClick(e) {
    let index = e.currentTarget.dataset.index;

    this.setData({
      leftCategoryIndex: index,
      leftCategorySelect: this.data.leftCategroyArr[index],
      'requestParams.cid': this.data.leftCategroyArr[index].id,
      tempCategoryName: this.data.leftCategroyArr[index].name,
      'requestParams.page': 1,
      'requestParams.priceOrder': '',
      'requestParams.salesOrder': '',
      'requestParams.news': 0
    })
    this.queryCategoryProductList(true, 'refresh');
  },
  // 排序切换
  simpleSortChange(e) {
    console.log("JJLog:哈哈哈哈:" + JSON.stringify(e));
    let detail = e.detail;
    switch (detail.key) {
      case 'all':
        this.setData({
          'requestParams.priceOrder': '',
          'requestParams.salesOrder': '',
          'requestParams.news': 0,
          'requestParams.page': 1,
          isBottomShow: false,
        })
        break;
      case 'price':
        this.setData({
          'requestParams.priceOrder': detail.sortType,
          'requestParams.salesOrder': '',
          'requestParams.news': 0,
          'requestParams.page': 1,
          isBottomShow: false,
        })
        break;
      case 'sale':
        this.setData({
          'requestParams.priceOrder': '',
          'requestParams.salesOrder': detail.sortType,
          'requestParams.news': 0,
          'requestParams.page': 1,
          isBottomShow: false,
        })
        break;
      case 'new':
        this.setData({
          'requestParams.priceOrder': '',
          'requestParams.salesOrder': '',
          'requestParams.news': 1,
          'requestParams.page': 1,
          isBottomShow: false,
        })
        break;

      default:
        break;
    }
    this.queryCategoryProductList(true, 'refresh');
  },


  // 下拉刷新
  handleRefresh() {
    // TODO
    this.setData({
      'requestParams.page': 1,
      isBottomShow: false,
      refreshFlag: true,
    })
    this.queryCategoryProductList(true, 'refresh');
  },
  // 加载更多
  handleLoadmore() {
    console.log('加载更多');
    if (this.data.isBottomShow || this.data.showRecommendPro) {
      return;
    }
    this.setData({
      isShowLoading: true,
      'requestParams.page': this.data.requestParams.page + 1,
    })
    this.queryCategoryProductList(true);
  },


  //获取所有分类
  queryAllCategory() {
    wx.showLoading();
    queryAllCategory().then(res => {
      // console.log("JJLog:分类列表===:" + JSON.stringify(res));
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          topScrollArr: res.data || []
        })
        let arr = []
        //这个没值证明是点击分类过来的，默认啥都取第一个
        if (!app.globalData.categoryName) {
          arr = res.data[0].child || [];
          arr = [{ id: res.data[0].id, name: "全部" }, ...arr]
          if (arr.length > 0) {


            this.setData({
              leftCategroyArr: arr,
              'requestParams.cid': arr[0].id,
              tempCategoryName: arr[0].name
            })
            this.queryCategoryProductList(false, "refresh");
          }
        } else {
          //遍历处理:
          res.data.forEach((i, index) => {
            if (i.name == app.globalData.categoryName) {
              arr = i.child || [];
              arr = [{ id: res.data[index].id, name: "全部" }, ...arr]
              this.setData({
                topCategoryIndex: index
              })
            }
          })

          app.globalData.categoryName = null;
          if (arr.length > 0) {

            this.setData({
              leftCategroyArr: arr,
              'requestParams.cid': arr[0].id,
              tempCategoryName: arr[0].name
            })
            this.queryCategoryProductList(false, "refresh");
          }


        }

      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:queryAllCategory", err);
    })
  },

  //loadingType决定是否需要loading,type决定是否是刷新
  queryCategoryProductList(loadingType, type) {
    if (loadingType) {
      wx.showLoading();
    }
    queryCategoryProductList(this.data.requestParams).then(res => {
      wx.hideLoading()
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.productList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          productList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.requestParams.page ? true : false,
        })
        console.log('JJLog:查询参数是：' + JSON.stringify(this.data.requestParams));
        console.log('JJLog:tempCategoryName:' + this.data.tempCategoryName);
        if (this.data.tempCategoryName == '全部') {
          let fourArr = arr.slice(0, 4);
          this.setData({
            recomendProductList: fourArr || []
          })
        }
        if (arr.length < 1) {
          console.log("JJLog:这边东西为空了======");
          this.setData({
            showRecommendPro: true,
          })
        } else {
          this.setData({
            showRecommendPro: false,
          })
        }
      }
    }).catch(err => {
      wx.hideLoading()
      if (this.data.requestParams.page != 1) {
        this.setData({
          'requestParams.page': this.data.requestParams.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error("JJLog:queryCategoryProductList", err);
    })
  },

  topCategoryChange(e) {
    let index = e.currentTarget.dataset.index;
    // let leftMargin = this.data.topScrollArr[index].left - this.data.topContentScrollW / 2 + this.data.topScrollArr[index].width / 2
    // console.log("JJLog:看第一个值：" + this.data.topScrollArr[index].left);
    // console.log("JJlog:第二个值：" + this.data.topContentScrollW);
    // console.log("JJLog:第三个只：" + this.data.topScrollArr[index].width)
    // console.log("JJLog:看看这个是啥：" + leftMargin);
    let leftMargin = 0;
    if (index < 4) {
      if (index < 2) {
        leftMargin = index * 20
      } else {
        leftMargin = index * 50
      }
    } else {
      leftMargin = index * 50
    }
    this.setData({
      topCategoryIndex: index,
      topCategoryNextIndex: index + 1,
      topCategoryItem: this.data.topScrollArr[index],
      topCategoryShow: false,
      horizontalSwiperIndex: index,
      topScrollLeft: leftMargin,
      leftCategoryIndex: 0,
    })
    let childArr = this.data.topCategoryItem.child || []
    if (childArr.length > 0) {
      if (childArr[0].name != '全部') {
        childArr = [{ id: this.data.topCategoryItem.id, name: '全部' }, ...childArr]
      }
      this.setData({
        leftCategroyArr: childArr,
        'requestParams.cid': childArr[0].id,
        tempCategoryName: childArr[0].name,
        'requestParams.page': 1,
        'requestParams.priceOrder': '',
        'requestParams.salesOrder': '',
        'requestParams.news': 0,
        isBottomShow: false,
      })
      this.queryCategoryProductList(true, 'refresh');
    }
  },
  showTopCategoryClick() {
    this.setData({
      topCategoryShow: !this.data.topCategoryShow
    })
  },
  ininScrollW() {
    //获取对象
    const query = wx.createSelectorQuery()
    //获取节点信息
    query.select('.topCategory-scroll').boundingClientRect(data => {
      // 拿到 scroll-view 组件宽度
      this.setData({
        topContentScrollW: data.width
      })
    }).exec();
    //拿到所有item的宽度和
    query.selectAll('.top-scroll-item').boundingClientRect(data => {
      let dataLen = data.length;
      let arr = this.data.topScrollArr;
      for (let i = 0; i < dataLen; i++) {
        //  scroll-view 子元素组件距离左边栏的距离
        arr[i].left = data[i].left;
        //  scroll-view 子元素组件宽度
        arr[i].width = data[i].width
      }
      this.setData({
        topScrollArr: arr
      })
    }).exec()


  },


})